package Day2025_02_23;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

public class MyTimer {
    private BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    private Object lock = new Object();
    public MyTimer(int capacity) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    synchronized (lock) {
                        while (queue.isEmpty()) lock.wait();
                    }
                    MyTask task = queue.take();
                    long currentTime = System.currentTimeMillis();
                    if (currentTime >= task.getTime()) task.getRunnable().run();
                    else {
                        queue.put(task);
                        long waitTime = task.getTime() - currentTime;
                        synchronized (lock) {
                            lock.wait(waitTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "定时器");
        thread.start();

        Thread daemonThread = new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    lock.notifyAll();
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        daemonThread.setDaemon(true);
        daemonThread.start();
    }

    public void schedule (Runnable runnable, long time) throws InterruptedException {
        MyTask myTask = new MyTask(runnable, time);
        queue.put(myTask);
        synchronized (lock) {
            lock.notifyAll();
        }
    }
}

class MyTask implements Comparable<MyTask> {
    private Runnable runnable;
    private long time;
    public MyTask(Runnable runnable, long time) {
        if (runnable == null) {
            throw new IllegalArgumentException("执行任务不能为空");
        }
        if (time < 0) {
            throw new IllegalArgumentException("执行时间不能小于零");
        }
        this.runnable = runnable;
        this.time = time + System.currentTimeMillis();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        if (o.time < this.time) return 1;
        else if (o.time > this.time) return -1;
        else return 0;
    }
}